const { sequelize } = require("../db/index")
const { DataTypes, Model } = require("sequelize")
const User = require("./user_model")
const Cleaner = require("./cleaner_model")
const moment = require('moment');

class Dict extends Model {
  static async hasDict(id) {
    const cate = await Dict.findOne({ where: { id } })
    if (cate === null) {
      return false
    } else {
      return true
    }
  }
  static async createDict({ cat_name, parent_id, is_show, sort, data_flag }) {
    const cate = await Dict.findOrCreate({ where: {cat_name}, defaults:{ cat_name, parent_id, is_show, sort, data_flag } })
    return cate
  }

  static async addAdmin(buildingId, userId) {
    try {
      const cate = await Dict.findOne({ where: { id: buildingId } })
      const user = await User.findOne({ where: { id: userId } })
      const result = await cate.addAdmin(user)
      return result
    } catch (e) {
      throw new Error("已存在该管理员，添加失败")
    }
  }
  static async addCleaner(buildingId, cleanerId) {
    try {
      const cleaner = await Cleaner.findOne({ where: { id: cleanerId } })
      cleaner.buildingId = buildingId
      return await cleaner.save()
    } catch (e) {
      throw new Error("添加保洁员失败")
    }
  }
  static async addFloor(buildingId, floor) {
    try {
      floor.buildingId = buildingId
      return await floor.save()
    } catch (error) {
      console.log(error)
    }
  }
}

Dict.init(
  {
    id: {
      comment: "ID",
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
      allowNull: false
    },
    store_id: {
      comment: "门店id",
      type: DataTypes.INTEGER,
    },
    name: {
      comment: "字典名称",
      type: DataTypes.STRING,
      autoIncrement: false,
      allowNull: false
    },
    remark: {
      comment: "描述",
      type: DataTypes.STRING,
      autoIncrement: false,
      allowNull: false
    },
    create_time: {
      comment: "创建时间",
      type: DataTypes.DATE
    }
  },
  {
    sequelize,
    modelName: "sys_dict",
    freezeTableName: true,
    paranoid: false,
    timestamps: false
  }
)

module.exports = Dict
